package com.sunhao.springboot_satoken.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.code.kaptcha.Producer;
import com.sunhao.springboot_satoken.domain.dos.CaptchaDo;
import com.sunhao.springboot_satoken.mapper.CaptchaMapper;
import com.sunhao.springboot_satoken.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName captchaServiceImpl
 * @Description
 * @Author SunHao
 * @Date 2025/7/26 8:27
 * @Version 1.0
 **/
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CaptchaMapper captchaMapper;

    // 验证码过期时间：5分钟
    private static final int CAPTCHA_EXPIRE_MINUTES = 5;

    // Redis存储前缀
    private static final String CAPTCHA_KEY_PREFIX = "captcha:";


    @Override
    public Boolean validateCaptcha(String captchaKey, String captcha) {
        if (captchaKey == null || captcha == null) {
            return false;
        }

        //从redis获取正确验证码
        String key = CAPTCHA_KEY_PREFIX + captchaKey;
        String correctCaptcha = redisTemplate.opsForValue().get(key);


        redisTemplate.delete(key);

        // 验证码不存在或已过期
        if (correctCaptcha == null) {
            return false;
        }
        return correctCaptcha.equalsIgnoreCase(captcha);
    }

    @Override
    public String generateCaptchKey() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    @Override
    public byte[] generateCaptchaImage(String captchaKey) {
        //生成验证文本
        String captchText = kaptchaProducer.createText();

        //生成验证码图片
        BufferedImage image = kaptchaProducer.createImage(captchText);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            // 修正格式名称，移除前面的点
            ImageIO.write(image, "png", byteArrayOutputStream);
        } catch (IOException e) {
            // 记录异常并抛出运行时异常，避免返回空字节数组
            e.printStackTrace();
            throw new RuntimeException("生成验证码图片失败", e);
        }

        Date expireTime = new Date(System.currentTimeMillis() + CAPTCHA_EXPIRE_MINUTES * 60 * 1000);
        
        // 先删除已存在的相同captchaKey的记录，避免唯一键冲突
        captchaMapper.delete(new LambdaQueryWrapper<CaptchaDo>().eq(CaptchaDo::getCaptchaKey, captchaKey));
        
        // 创建并插入新的验证码记录
        CaptchaDo captchaDo = new CaptchaDo();
        captchaDo.setExpireTime(expireTime);
        captchaDo.setCaptchaKey(captchaKey);
        captchaDo.setCaptchaValue(captchText);
        captchaMapper.insert(captchaDo);

        //存储到redis，设置过期时间
        redisTemplate.opsForValue().set(CAPTCHA_KEY_PREFIX + captchaKey,
                captchText,
                CAPTCHA_EXPIRE_MINUTES,
                TimeUnit.MINUTES
        );

        return byteArrayOutputStream.toByteArray();
    }



}
